package com.wsl.encry;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.AES;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.SelectionModel;
import com.intellij.openapi.ui.Messages;
import javax.crypto.spec.SecretKeySpec;

public class EncryptAction extends AnAction {
    MyPluginState state = ServiceManager.getService(MyPluginState.class);
    @Override
    public void actionPerformed(AnActionEvent e) {
        final Editor editor = e.getRequiredData(CommonDataKeys.EDITOR);
        final SelectionModel selectionModel = editor.getSelectionModel();
        final String selectedText = selectionModel.getSelectedText();
        System.out.println("选中的文本："+selectedText);
        if (selectedText != null && !selectedText.isEmpty()) {
            final String key = state.getKey(); // 获取密钥
            if (StrUtil.isEmpty(key)) {
                Messages.showMessageDialog("请先配置密钥","提醒", Messages.getInformationIcon());
                throw new IllegalStateException("Key not set");
            }
            System.out.println("加密key:"+ key);
            String encryptedText = encrypt(selectedText, key); // 加密文本
            System.out.println("加密后的文本："+encryptedText);
            //默认加两个反斜杠
            encryptedText="//"+encryptedText;
            replaceText(editor, encryptedText);
        }
    }
    
    private String encrypt(String data, String key) {
        try {
            AES aes=null;
            if(StrUtil.isNotEmpty(key)){
                while (key.length() < 16) {
                    key += '\0';
                }
                byte[] keyBytes = key.getBytes(); // 将密钥字符串转换为字节
                // 生成AES密钥
                SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, "AES");
                // 创建AES对象
                 aes = SecureUtil.aes(secretKeySpec.getEncoded());
            }else{
                 aes = SecureUtil.aes();
            }

            // 加密
            String encryptHex = aes.encryptHex(data);
            return encryptHex;
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }

    private void replaceText(Editor editor, String newText) {
        final Document document = editor.getDocument();
        final int startOffset = editor.getSelectionModel().getSelectionStart();
        final int endOffset = editor.getSelectionModel().getSelectionEnd();

        WriteCommandAction.runWriteCommandAction(editor.getProject(), () -> {
            document.replaceString(startOffset, endOffset, newText);
        });
    }
    

}